<script setup>
import { Message, MessageBox } from 'element-ui';
import { cloneDeep } from 'lodash-es';
import { getToken } from '@/utils/auth';
import { useGlobalState } from '@/store/globalState.js';
import { useWatch, useResetForm } from '@/hooks';
const props = defineProps({
  title: { type: String, default: () => '' },
  submit: { type: Number, default: 0 },
  cancel: { type: Boolean, default: false },
  formData: { type: Object, default: () => null },
});
const emit = defineEmits(['handleSuccess']);
const upload = ref({
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: useGlobalState().globalState.fileUrl + '/file/uploadFile',
  url2: useGlobalState().globalState.fileUrl + props.uploadUrl,
});
const editForm = ref(null);
const editParams = ref({
  fileName: null,
  fileInfo: null,
  fileUrl: null,
  fileType: null,
});
const uploadFile = ref(null);
const fileLists = ref([]);
const typeOptions = [
  { value: '全部', label: '全部' },
  { value: '收资信息', label: '收资信息' },
  { value: '项目合同', label: '项目合同' },
  { value: '可行性研究报告', label: '可行性研究报告' },
  { value: '能源审计报告', label: '能源审计报告' },
  { value: '项目立项批复文件', label: '项目立项批复文件' },
  { value: '补充协议', label: '补充协议' },
  { value: '项目成分干系表', label: '项目成分干系表' },
  { value: '项目资产信息', label: '项目资产信息' },
  { value: '其他', label: '其他' },
];

const handleAvatarSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    fileLists.value = fileList;
    editParams.value.fileName = file.name;
    editParams.value.fileUrl = res.data.url;
  } else {
    Message.error('上传失败，请重新上传');
    fileLists.value.splice(0, 1);
    uploadFile.value.clearFiles();
  }
};
const handleAvatarErroe = (err, file, fileList) => {
  Message({
    type: 'error',
    message: err?.msg ?? '上传失败，请重新上传',
  });
  fileLists.value.splice(0, 1);
  uploadFile.value.clearFiles();
};
const handleUploadChange = (file, fileList) => {
  fileLists.value = fileList;
};
const handleRemove = () => {
  fileLists.value = [];
};
// 超出限制上传数量回调
const handleExceed = () => {
  Message({
    type: 'warning',
    message: '当前限制最大上传数量：1 ,上传新的文件之前请先删除原文件！',
  });
};
useWatch(
  () => props.submit,
  n => {
    if (n) {
      editForm.value.validate(valid => {
        if (valid) {
          if (fileLists.value?.length > 0) {
            MessageBox.confirm('请确认信息无误', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning',
            }).then(() => {
              emit('handleSuccess', editParams.value);
              useResetForm(editForm);
              editParams.value = {
                fileName: null,
                fileInfo: null,
                fileUrl: null,
                fileType: null,
              };
              fileLists.value = [];
            });
          } else {
            Message.warning('请上传附件文件');
          }
        } else {
          return false;
        }
      });
    }
  },
);
useWatch(
  () => props.cancel,
  n => {
    if (n === false) {
      // useResetForm(editForm);
      // editParams.value = {
      //   fileName: null,
      //   fileInfo: null,
      //   fileUrl: null,
      // };
      // fileLists.value = [];
    }
  },
  { deep: true, immediate: true },
);
useWatch(
  () => props.formData,
  (n, o) => {
    if (n) {
      editParams.value = cloneDeep(n);
      fileLists.value = [
        {
          name: n.fileName,
          url: useGlobalState().globalState.serverUrl + n.fileUrl,
        },
      ];
    } else {
      useResetForm(editForm);
      editParams.value = {
        fileName: null,
        fileInfo: null,
        fileUrl: null,
        fileType: null,
      };
      fileLists.value = [];
    }
  },
  { deep: true, immediate: true },
);
</script>
<template>
  <div>
    <el-form ref="editForm" :model="editParams" size="small" label-width="100px" class="queryForm u-p20">
      <el-form-item
        label="档案类型"
        prop="fileType"
        :rules="{
          required: true,
          message: '请选择档案类型',
          trigger: ['blur', 'change'],
        }"
      >
        <div class="u-df-st" style="align-items: flex-start">
          <el-select v-model="editParams.fileType" placeholder="请选择档案类型">
            <el-option v-for="item in typeOptions" :key="item.value" :value="item.value" :label="item.label">
              {{ item.value }}
            </el-option>
          </el-select>
          <el-upload
            class="upload-demo u-ml10"
            ref="uploadFile"
            :action="upload.url"
            :headers="upload.headers"
            accept=".pdf"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarErroe"
            :on-change="handleUploadChange"
            :on-remove="handleRemove"
            :file-list="fileLists"
            :auto-upload="true"
            :limit="1"
            :on-exceed="handleExceed"
            :disabled="title === '编辑'"
          >
            <el-button
              :disabled="title === '编辑'"
              size="small"
              plain
              class="el-icon-upload2"
              type="primary"
              style="font-size: 14px"
            >
              点击上传文件
            </el-button>
            <div v-if="fileLists.length === 0" slot="tip" class="el-upload__tip u-ml10 u-text">格式：pdf</div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item
        label="文件说明："
        prop="fileInfo"
        :rules="{
          required: true,
          message: '请输入文件说明，说明内容“记录时间+文件用途+结论”',
          trigger: ['blur', 'change'],
        }"
      >
        <el-input
          type="textarea"
          placeholder="记录时间+文件用途+结论"
          v-model="editParams.fileInfo"
          maxlength="200"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
.el-upload__tip {
  display: inline-block;
}

.app-dark .queryForm ::v-deep(.el-textarea__inner) {
  background: rgba(0, 0, 0, 0.5);
  border: 1px solid #262f48;
}

.upload-demo ::v-deep(.el-upload-list) {
  margin-left: -81%;
}
</style>
